package com.cheng.im.service.friendship.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheng.im.common.constants.SeqConstants;
import com.cheng.im.service.common.eunms.AllowFriendTypeEnum;
import com.cheng.im.service.common.eunms.CheckFriendShipTypeEnum;
import com.cheng.im.service.common.eunms.FriendShipErrorCode;
import com.cheng.im.service.common.eunms.FriendShipStatusEnum;
import com.cheng.im.service.common.exception.ApplicationException;
import com.cheng.im.service.common.model.RequestBase;
import com.cheng.im.service.common.model.SyncReq;
import com.cheng.im.service.common.model.SyncResp;
import com.cheng.im.service.common.resp.CommonResult;
import com.cheng.im.service.friendship.mapper.ImFriendshipMapper;
import com.cheng.im.service.friendship.service.ImFriendshipRequestService;
import com.cheng.im.service.friendship.service.ImFriendshipService;
import com.cheng.im.service.frienship.domain.ImFriendship;
import com.cheng.im.service.frienship.model.req.*;
import com.cheng.im.service.frienship.model.resp.CheckFriendShipResp;
import com.cheng.im.service.frienship.model.resp.ImportFriendShipResp;
import com.cheng.im.service.redis.seq.RedisSeq;
import com.cheng.im.service.redis.seq.WriteUserSeq;
import com.cheng.im.service.user.domain.ImUserData;
import com.cheng.im.service.user.service.ImUserDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.omg.CORBA.BAD_CONTEXT;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author Cheng
* @description 针对表【im_friendship】的数据库操作Service实现
* @createDate 2024-12-17 15:04:33
*/
@DubboService
public class ImFriendshipServiceImpl extends ServiceImpl<ImFriendshipMapper, ImFriendship>
    implements ImFriendshipService {

    @Resource
    private ImUserDataService imUserDataService;
    @Resource
    private ImFriendshipRequestService imFriendShipRequestService;
    @Resource
    RedisSeq redisSeq;
    @Resource
    WriteUserSeq writeUserSeq;

    @Override
    public CommonResult<ImportFriendShipResp> importFriendShip(ImporFriendShipReq req) {
        if(req.getFriendItem().size() > 100){
            return CommonResult.failed(FriendShipErrorCode.IMPORT_SIZE_BEYOND);
        }
        ImportFriendShipResp resp = new ImportFriendShipResp();
        List<String> successId = new ArrayList<>();
        List<String> errorId = new ArrayList<>();

        // todo: 没有检查被加的好友是否存在
        for (ImporFriendShipReq.ImportFriendDto dto : req.getFriendItem()) {
            ImFriendship entity = new ImFriendship();
            BeanUtils.copyProperties(dto,entity);
            entity.setAppId(req.getAppId());
            entity.setFromId(req.getFromId());
            try {
                int insert = baseMapper.insert(entity);
                if(insert == 1){
                    successId.add(dto.getToId());
                }else{
                    errorId.add(dto.getToId());
                }
            }catch (Exception e){
                e.printStackTrace();
                errorId.add(dto.getToId());
            }

        }

        resp.setErrorId(errorId);
        resp.setSuccessId(successId);

        return CommonResult.success(resp);
    }

    @Override
    public CommonResult addFriend(AddFriendReq req) {

        // 1. 检查用户的合法性
        CommonResult<ImUserData> fromInfo = imUserDataService.getSingleUserInfo(req.getFromId(), req.getAppId());
        if(!fromInfo.isOk()){
            return fromInfo;
        }

        CommonResult<ImUserData> toInfo = imUserDataService.getSingleUserInfo(req.getToItem().getToId(), req.getAppId());
        if(!toInfo.isOk()){
            return toInfo;
        }

        // 2. todo: 回调
//        if(appConfig.isAddFriendBeforeCallback()){
//            ResponseVO callbackResp = callbackService
//                    .beforeCallback(req.getAppId(),
//                            Constants.CallbackCommand.AddFriendBefore
//                            ,JSONObject.toJSONString(req));
//            if(!callbackResp.isOk()){
//                return callbackResp;
//            }
//        }

        ImUserData data = toInfo.getData();

        // 判断添加的用户设置是否允许添加
        if(data.getFriendAllowType() != null && data.getFriendAllowType() == AllowFriendTypeEnum.NOT_NEED.getCode()){
            return this.doAddFriend(req,req.getFromId(), req.getToItem(), req.getAppId());
        }else{

            LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
            query.eq(ImFriendship::getAppId, req.getAppId());
            query.eq(ImFriendship::getFromId,req.getFromId());
            query.eq(ImFriendship::getToId, req.getToItem().getToId());
            ImFriendship fromItem = baseMapper.selectOne(query);

            if(fromItem == null || fromItem.getStatus()
                    != FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode()){
                // 插入一条好友申请的数据
                CommonResult responseVO = imFriendShipRequestService.addFriendshipRequest(req.getFromId(), req.getToItem(), req.getAppId());
                if(!responseVO.isOk()){
                    return responseVO;
                }
            }else{
                return CommonResult.failed(FriendShipErrorCode.TO_IS_YOUR_FRIEND);
            }

        }

        return CommonResult.success();
    }

    @Override
    public CommonResult updateFriend(UpdateFriendReq req) {
        CommonResult<ImUserData> fromInfo = imUserDataService.getSingleUserInfo(req.getFromId(), req.getAppId());
        if(!fromInfo.isOk()){
            return fromInfo;
        }

        CommonResult<ImUserData> toInfo = imUserDataService.getSingleUserInfo(req.getToItem().getToId(), req.getAppId());
        if(!toInfo.isOk()){
            return toInfo;
        }

        CommonResult responseVO = this.doUpdate(req.getFromId(), req.getToItem(), req.getAppId());

        if(responseVO.isOk()){
            // todo: 通知im
//            UpdateFriendPack updateFriendPack = new UpdateFriendPack();
//            updateFriendPack.setRemark(req.getToItem().getRemark());
//            updateFriendPack.setToId(req.getToItem().getToId());
//            messageProducer.sendToUser(req.getFromId(),
//                    req.getClientType(),req.getImei(),FriendshipEventCommand
//                            .FRIEND_UPDATE,updateFriendPack,req.getAppId());
//
//            if (appConfig.isModifyFriendAfterCallback()) {
//                AddFriendAfterCallbackDto callbackDto = new AddFriendAfterCallbackDto();
//                callbackDto.setFromId(req.getFromId());
//                callbackDto.setToItem(req.getToItem());
//                callbackService.beforeCallback(req.getAppId(),
//                        Constants.CallbackCommand.UpdateFriendAfter, JSONObject
//                                .toJSONString(callbackDto));
//            }
        }
        return responseVO;
    }

    @Override
    @Transactional
    public CommonResult doUpdate(String fromId, FriendDto dto,String appId){

         long seq = redisSeq.doGetSeq(appId + ":" + SeqConstants.FRIENDSHIP);

        UpdateWrapper<ImFriendship> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(ImFriendship::getAddSource, dto.getAddSource())
                .set(ImFriendship::getExtra, dto.getExtra())
//                .set(ImFriendShip::getFriendSequence, seq)
                .set(ImFriendship::getRemark, dto.getRemark())
                .eq(ImFriendship::getAppId, appId)
                .eq(ImFriendship::getToId, dto.getToId())
                .eq(ImFriendship::getFromId, fromId);

        int update = baseMapper.update(null, updateWrapper);
        if(update == 1){
            //之后回调
//            if (appConfig.isModifyFriendAfterCallback()){
//                AddFriendAfterCallbackDto callbackDto = new AddFriendAfterCallbackDto();
//                callbackDto.setFromId(fromId);
//                callbackDto.setToItem(dto);
//                callbackService.beforeCallback(appId,
//                        Constants.CallbackCommand.UpdateFriendAfter, JSONObject
//                                .toJSONString(callbackDto));
//            }

            writeUserSeq.writeUserSeq(appId,fromId, SeqConstants.FRIENDSHIP, seq);
            return CommonResult.success(null);
        }

        return CommonResult.failed();
    }

    @Override
    public CommonResult deleteFriend(DeleteFriendReq req) {
        LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendship::getAppId,req.getAppId());
        query.eq(ImFriendship::getFromId,req.getFromId());
        query.eq(ImFriendship::getToId,req.getToId());

        ImFriendship fromItem = baseMapper.selectOne(query);
        if(fromItem == null){
            return CommonResult.failed(FriendShipErrorCode.TO_IS_NOT_YOUR_FRIEND);
        }else{
            if(fromItem.getStatus() != null && fromItem.getStatus() == FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode()){
                ImFriendship update = new ImFriendship();

                long seq = redisSeq.doGetSeq(req.getAppId() + ":" + SeqConstants.FRIENDSHIP);
                update.setFriendSequence(seq);
                update.setStatus(FriendShipStatusEnum.FRIEND_STATUS_DELETE.getCode());
                baseMapper.update(update,query);
                // todo: 删除好友通知
                writeUserSeq.writeUserSeq(req.getAppId(),req.getFromId(), SeqConstants.FRIENDSHIP, seq);
//                DeleteFriendPack deleteFriendPack = new DeleteFriendPack();
//                deleteFriendPack.setFromId(req.getFromId());
//                deleteFriendPack.setSequence(seq);
//                deleteFriendPack.setToId(req.getToId());
//                messageProducer.sendToUser(req.getFromId(),
//                        req.getClientType(), req.getImei(),
//                        FriendshipEventCommand.FRIEND_DELETE,
//                        deleteFriendPack, req.getAppId());

                //之后回调
//                if (appConfig.isAddFriendAfterCallback()){
//                    DeleteFriendAfterCallbackDto callbackDto = new DeleteFriendAfterCallbackDto();
//                    callbackDto.setFromId(req.getFromId());
//                    callbackDto.setToId(req.getToId());
//                    callbackService.beforeCallback(req.getAppId(),
//                            Constants.CallbackCommand.DeleteFriendAfter, JSONObject
//                                    .toJSONString(callbackDto));
//                }

            }else{
                return CommonResult.failed(FriendShipErrorCode.FRIEND_IS_DELETED);
            }
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult deleteAllFriend(DeleteFriendReq req) {
        LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendship::getAppId,req.getAppId());
        query.eq(ImFriendship::getFromId,req.getFromId());
        query.eq(ImFriendship::getStatus,FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode());

        ImFriendship update = new ImFriendship();
        update.setStatus(FriendShipStatusEnum.FRIEND_STATUS_DELETE.getCode());
        baseMapper.update(update,query);

        // todo:通知报文
//        DeleteAllFriendPack deleteFriendPack = new DeleteAllFriendPack();
//        deleteFriendPack.setFromId(req.getFromId());
//        messageProducer.sendToUser(req.getFromId(), req.getClientType(), req.getImei(), FriendshipEventCommand.FRIEND_ALL_DELETE,
//                deleteFriendPack, req.getAppId());

        return CommonResult.success();
    }

    @Override
    public CommonResult<List<ImFriendship>> getAllFriendShip(GetAllFriendShipReq req) {
        LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendship::getAppId,req.getAppId());
        query.eq(ImFriendship::getFromId,req.getFromId());
        return CommonResult.success(baseMapper.selectList(query));
    }

    @Override
    public CommonResult<ImFriendship> getRelation(GetRelationReq req) {
        LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendship::getAppId, req.getAppId());
        query.eq(ImFriendship::getFromId, req.getFromId());
        query.eq(ImFriendship::getToId, req.getToId());

        ImFriendship entity = baseMapper.selectOne(query);
        if(entity == null){
            return CommonResult.failed(FriendShipErrorCode.REPEATSHIP_IS_NOT_EXIST.getCode(),
                    FriendShipErrorCode.REPEATSHIP_IS_NOT_EXIST.getError());
        }
        return CommonResult.success(entity);
    }

    @Override
    @Transactional
    public CommonResult doAddFriend(RequestBase requestBase, String fromId, FriendDto dto, String appId) {
        //A-B
        //Friend表插入A 和 B 两条记录
        //查询是否有记录存在，如果存在则判断状态，如果是已添加，则提示已添加，如果是未添加，则修改状态

        LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendship::getAppId, appId);
        query.eq(ImFriendship::getFromId, fromId);
        query.eq(ImFriendship::getToId, dto.getToId());
        ImFriendship fromItem = baseMapper.selectOne(query);

        long seq = 0L;
        if(fromItem == null){
            //走添加逻辑。
            fromItem = new ImFriendship();
            fromItem.setAppId(appId);
            fromItem.setFriendSequence(seq);
            fromItem.setFromId(fromId);

            BeanUtils.copyProperties(dto,fromItem);
            fromItem.setStatus(FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode());
            fromItem.setCreateTime(System.currentTimeMillis());
            int insert = baseMapper.insert(fromItem);

            if(insert != 1){
                return CommonResult.failed(FriendShipErrorCode.ADD_FRIEND_ERROR.getCode(),
                        FriendShipErrorCode.ADD_FRIEND_ERROR.getError());
            }

             seq = redisSeq.doGetSeq(appId+":"+ SeqConstants.FRIENDSHIP);
             writeUserSeq.writeUserSeq(appId,fromId, SeqConstants.FRIENDSHIP, seq);
        } else{
            //如果存在则判断状态，如果是已添加，则提示已添加，如果是未添加，则修改状态

            if(fromItem.getStatus() == FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode()){
                return CommonResult.failed(FriendShipErrorCode.TO_IS_YOUR_FRIEND.getCode(),
                        FriendShipErrorCode.TO_IS_YOUR_FRIEND.getError());
            } else{
                ImFriendship update = new ImFriendship();

                if(StringUtils.isNotBlank(dto.getAddSource())){
                    update.setAddSource(dto.getAddSource());
                }

                if(StringUtils.isNotBlank(dto.getRemark())){
                    update.setRemark(dto.getRemark());
                }

                if(StringUtils.isNotBlank(dto.getExtra())){
                    update.setExtra(dto.getExtra());
                }

                update.setFriendSequence(seq);
                update.setStatus(FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode());

                int result = baseMapper.update(update, query);
                if(result != 1){
                    return CommonResult.failed(FriendShipErrorCode.ADD_FRIEND_ERROR.getCode(),
                            FriendShipErrorCode.ADD_FRIEND_ERROR.getError());
                }

                 seq = redisSeq.doGetSeq(appId+":"+ SeqConstants.FRIENDSHIP);
                 writeUserSeq.writeUserSeq(appId,fromId, SeqConstants.FRIENDSHIP, seq);
            }

        }

        // 走判断对方有没有加你逻辑
        LambdaQueryWrapper<ImFriendship> toQuery = new LambdaQueryWrapper<>();
        toQuery.eq(ImFriendship::getAppId, appId);
        toQuery.eq(ImFriendship::getFromId, dto.getToId());
        toQuery.eq(ImFriendship::getToId, fromId);
        ImFriendship toItem = baseMapper.selectOne(toQuery);

        if(toItem == null){
            toItem = new ImFriendship();
            toItem.setAppId(appId);
            toItem.setFromId(dto.getToId());
            BeanUtils.copyProperties(dto,toItem);
            toItem.setToId(fromId);
            toItem.setFriendSequence(seq);
            toItem.setStatus(FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode());
            toItem.setCreateTime(System.currentTimeMillis());
//            toItem.setBlack(FriendShipStatusEnum.BLACK_STATUS_NORMAL.getCode());
            int insert = baseMapper.insert(toItem);

            writeUserSeq.writeUserSeq(appId,dto.getToId(), SeqConstants.FRIENDSHIP, seq);
        }else{
            if(FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode() !=
                    toItem.getStatus()){
                ImFriendship update = new ImFriendship();
                update.setFriendSequence(seq);
                update.setStatus(FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode());
                baseMapper.update(update,toQuery);

                writeUserSeq.writeUserSeq(appId,dto.getToId(), SeqConstants.FRIENDSHIP, seq);
            }
        }

        // 发送给from  todo: 添加好友的通知报文，应该由这个服务端发送到消息队列，然后由im消费进行通知
//        AddFriendPack addFriendPack = new AddFriendPack();
//        BeanUtils.copyProperties(fromItem,addFriendPack);
//        addFriendPack.setSequence(seq);
//        if(requestBase != null){
//            messageProducer.sendToUser(fromId,requestBase.getClientType(),
//                    requestBase.getImei(), FriendshipEventCommand.FRIEND_ADD,addFriendPack
//                    ,requestBase.getAppId());
//        }else {
//            messageProducer.sendToUser(fromId,
//                    FriendshipEventCommand.FRIEND_ADD,addFriendPack
//                    ,requestBase.getAppId());
//        }
//
//        AddFriendPack addFriendToPack = new AddFriendPack();
//        BeanUtils.copyProperties(toItem,addFriendPack);
//        messageProducer.sendToUser(toItem.getFromId(),
//                FriendshipEventCommand.FRIEND_ADD,addFriendToPack
//                ,requestBase.getAppId());
//
//        //之后回调
//        if (appConfig.isAddFriendAfterCallback()){
//            AddFriendAfterCallbackDto callbackDto = new AddFriendAfterCallbackDto();
//            callbackDto.setFromId(fromId);
//            callbackDto.setToItem(dto);
//            callbackService.beforeCallback(appId,
//                    Constants.CallbackCommand.AddFriendAfter, JSONObject
//                            .toJSONString(callbackDto));
//        }

        return CommonResult.success();
    }

    @Override
    public CommonResult<List<CheckFriendShipResp>> checkFriendship(CheckFriendShipReq req) {
        Map<String, Integer> result = req.getToIds().stream()
                .collect(Collectors.toMap(Function.identity(), s -> 0));

        List<CheckFriendShipResp> resp;

        if(req.getCheckType() == CheckFriendShipTypeEnum.SINGLE.getType()){
            resp =baseMapper.checkFriendShip(req);
        }else {
            resp =baseMapper.checkFriendShipBoth(req);
        }

        Map<String, Integer> collect = resp.stream()
                .collect(Collectors.toMap(CheckFriendShipResp::getToId, CheckFriendShipResp::getStatus));

        for (String toId : result.keySet()){
            if(!collect.containsKey(toId)){
                CheckFriendShipResp checkFriendShipResp = new CheckFriendShipResp();
                checkFriendShipResp.setFromId(req.getFromId());
                checkFriendShipResp.setToId(toId);
                checkFriendShipResp.setStatus(result.get(toId));
                resp.add(checkFriendShipResp);
            }
        }

        return CommonResult.success(resp);
    }

    @Override
    public CommonResult addBlack(AddFriendShipBlackReq req) {
        CommonResult<ImUserData> fromInfo = imUserDataService.getSingleUserInfo(req.getFromId(), req.getAppId());
        if(!fromInfo.isOk()){
            return fromInfo;
        }

        CommonResult<ImUserData> toInfo = imUserDataService.getSingleUserInfo(req.getToId(), req.getAppId());
        if(!toInfo.isOk()){
            return toInfo;
        }

        LambdaQueryWrapper<ImFriendship> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendship::getAppId,req.getAppId());
        query.eq(ImFriendship::getFromId,req.getFromId());
        query.eq(ImFriendship::getToId,req.getToId());

        ImFriendship fromItem = baseMapper.selectOne(query);
        Long seq = 0L;
        if(fromItem == null){
            //走添加逻辑。
            seq = redisSeq.doGetSeq(req.getAppId() + ":" + SeqConstants.FRIENDSHIP);

            fromItem = new ImFriendship();
            fromItem.setFromId(req.getFromId());
            fromItem.setToId(req.getToId());
            fromItem.setFriendSequence(seq);
            fromItem.setAppId(req.getAppId());
            fromItem.setBlack(FriendShipStatusEnum.BLACK_STATUS_BLACKED.getCode());
            fromItem.setCreateTime(System.currentTimeMillis());
            int insert = baseMapper.insert(fromItem);
            if(insert != 1){
                return CommonResult.failed(FriendShipErrorCode.ADD_FRIEND_ERROR);
            }
            writeUserSeq.writeUserSeq(req.getAppId(),req.getFromId(), SeqConstants.FRIENDSHIP, seq);

        } else{
            // 如果存在则判断状态，如果是拉黑，则提示已拉黑，如果是未拉黑，则修改状态
            if(fromItem.getBlack() != null && fromItem.getBlack() == FriendShipStatusEnum.BLACK_STATUS_BLACKED.getCode()){
                return CommonResult.failed(FriendShipErrorCode.FRIEND_IS_BLACK);
            }

            else {
                seq = redisSeq.doGetSeq(req.getAppId() + ":" + SeqConstants.FRIENDSHIP);

                ImFriendship update = new ImFriendship();
                update.setFriendSequence(seq);
                update.setBlack(FriendShipStatusEnum.BLACK_STATUS_BLACKED.getCode());
                int result = baseMapper.update(update, query);
                if(result != 1){
                    return CommonResult.failed(FriendShipErrorCode.ADD_BLACK_ERROR);
                }
                writeUserSeq.writeUserSeq(req.getAppId(),req.getFromId(), SeqConstants.FRIENDSHIP, seq);
            }
        }

        // todo: 拉黑通知
//        AddFriendBlackPack addFriendBlackPack = new AddFriendBlackPack();
//        addFriendBlackPack.setFromId(req.getFromId());
//        addFriendBlackPack.setSequence(seq);
//        addFriendBlackPack.setToId(req.getToId());
//        //发送tcp通知
//        messageProducer.sendToUser(req.getFromId(), req.getClientType(), req.getImei(),
//                FriendshipEventCommand.FRIEND_BLACK_ADD, addFriendBlackPack, req.getAppId());
//
//        //之后回调
//        if (appConfig.isAddFriendShipBlackAfterCallback()){
//            AddFriendBlackAfterCallbackDto callbackDto = new AddFriendBlackAfterCallbackDto();
//            callbackDto.setFromId(req.getFromId());
//            callbackDto.setToId(req.getToId());
//            callbackService.beforeCallback(req.getAppId(),
//                    Constants.CallbackCommand.AddBlackAfter, JSONObject
//                            .toJSONString(callbackDto));
//        }

        return CommonResult.success();
    }

    @Override
    public CommonResult deleteBlack(DeleteBlackReq req) {

        LambdaQueryWrapper<ImFriendship> queryFrom = new LambdaQueryWrapper<>();
        queryFrom.eq(ImFriendship::getAppId, req.getAppId());
        queryFrom.eq(ImFriendship::getFromId, req.getFromId());
        queryFrom.eq(ImFriendship::getToId, req.getToId());

        ImFriendship fromItem = baseMapper.selectOne(queryFrom);
        if (fromItem.getBlack() != null && fromItem.getBlack() == FriendShipStatusEnum.BLACK_STATUS_NORMAL.getCode()) {
            throw new ApplicationException(FriendShipErrorCode.FRIEND_IS_NOT_YOUR_BLACK);
        }

        long seq = redisSeq.doGetSeq(req.getAppId() + ":" + SeqConstants.FRIENDSHIP);

        ImFriendship update = new ImFriendship();
        update.setFriendSequence(seq);

        update.setBlack(FriendShipStatusEnum.BLACK_STATUS_NORMAL.getCode());
        int update1 = baseMapper.update(update, queryFrom);
        if(update1 == 1){
            writeUserSeq.writeUserSeq(req.getAppId(),req.getFromId(), SeqConstants.FRIENDSHIP, seq);
//            DeleteBlackPack deleteFriendPack = new DeleteBlackPack();
//            deleteFriendPack.setFromId(req.getFromId());
//            deleteFriendPack.setSequence(seq);
//            deleteFriendPack.setToId(req.getToId());
//            messageProducer.sendToUser(req.getFromId(), req.getClientType(), req.getImei(), FriendshipEventCommand.FRIEND_BLACK_DELETE,
//                    deleteFriendPack, req.getAppId());
//
//            //之后回调
//            if (appConfig.isAddFriendShipBlackAfterCallback()){
//                AddFriendBlackAfterCallbackDto callbackDto = new AddFriendBlackAfterCallbackDto();
//                callbackDto.setFromId(req.getFromId());
//                callbackDto.setToId(req.getToId());
//                callbackService.beforeCallback(req.getAppId(),
//                        Constants.CallbackCommand.DeleteBlack, JSONObject
//                                .toJSONString(callbackDto));
//            }
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<List<CheckFriendShipResp>> checkBlack(CheckFriendShipReq req) {
        Map<String, Integer> toIdMap = req.getToIds().stream()
                .collect(Collectors.toMap(Function.identity(), s -> 0));

        List<CheckFriendShipResp> result = new ArrayList<>();
        if (req.getCheckType() == CheckFriendShipTypeEnum.SINGLE.getType()) {
            result = baseMapper.checkFriendShipBlack(req);
        } else {
            result = baseMapper.checkFriendShipBlackBoth(req);
        }

        Map<String, Integer> collect = result.stream()
                .collect(Collectors.toMap(CheckFriendShipResp::getToId, CheckFriendShipResp::getStatus));

        for (String toId : toIdMap.keySet()) {
            if(!collect.containsKey(toId)){
                CheckFriendShipResp checkFriendShipResp = new CheckFriendShipResp();
                checkFriendShipResp.setToId(toId);
                checkFriendShipResp.setFromId(req.getFromId());
                checkFriendShipResp.setStatus(toIdMap.get(toId));
                result.add(checkFriendShipResp);
            }
        }

        return CommonResult.success(result);
    }

    @Override
    public CommonResult<SyncResp<ImFriendship>> syncFriendshipList(SyncReq req) {
        if(req.getMaxLimit() > 100){
            req.setMaxLimit(100);
        }

        SyncResp<ImFriendship> resp = new SyncResp<>();
        //seq > req.getseq limit maxLimit
        LambdaQueryWrapper<ImFriendship> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImFriendship::getFromId, req.getOperator());
        queryWrapper.gt(ImFriendship::getFriendSequence, req.getLastSequence());
        queryWrapper.eq(ImFriendship::getAppId, req.getAppId());
        queryWrapper.last(" limit " + req.getMaxLimit());
        queryWrapper.orderByAsc(ImFriendship::getFriendSequence);
        List<ImFriendship> list = baseMapper.selectList(queryWrapper);

        if(!CollectionUtils.isEmpty(list)){
            ImFriendship maxSeqEntity = list.get(list.size() - 1);
            resp.setDataList(list);
            //设置最大seq
            Long friendShipMaxSeq = baseMapper.getFriendShipMaxSeq(req.getAppId(), req.getOperator());
            resp.setMaxSequence(friendShipMaxSeq);
            //设置是否拉取完毕
            resp.setCompleted(maxSeqEntity.getFriendSequence() >= friendShipMaxSeq);
            return CommonResult.success(resp);
        }

        resp.setCompleted(true);
        return CommonResult.success(resp);
    }

    @Override
    public List<String> getAllFriendId(String userId, String appId) {
        return baseMapper.getAllFriendId(userId, appId);
    }
}




